<template>
  <div class="common-skeleton">
    <template v-if="loading">
      <view className="skeletonCmpt">
        <view
          v-for="(item, index) in radiusList"
          :key="index"
          :style="{
            width: `${item.width}px`,
            height: `${item.height}px`,
            top: `${item.top}px`,
            left: `${item.left}px`,
          }"
          className="skeleton skeleton-radius skeleton-animate-gradient"
        />
        <view
          v-for="(item, index) in rectList"
          :key="index"
          :style="{
            width: `${item.width}px`,
            height: `${item.height}px`,
            top: `${item.top}px`,
            left: `${item.left}px`,
          }"
          className="skeleton skeleton-animate-gradien"
        />
      </view>
    </template>
  </div>
</template>

<script setup lang="ts">
import Taro from "@tarojs/taro";
import { onMounted, ref } from "vue";

defineOptions({
  name: "common-skeleton",
});

const props = withDefaults(
  defineProps<{
    loading?: boolean;
    selector?: string;
  }>(),
  {
    selector: "skeleton",
    loading: true,
  }
);

const radiusList = ref<any[]>([]);
const rectList = ref<any[]>([]);

onMounted(() => {
  initSkeleton();
});
const initSkeleton = () => {
  const { selector } = props;
  getGraphList(selector, `${selector}-radius`).then((res: any) => {
    console.log(res);
    radiusList.value = res;
  });

  getGraphList(selector, `${selector}-rect`).then((res: any) => {
    console.log(res);
    rectList.value = res;
  });
};

// 选择器获取节点
const getGraphList = (ancestor, descendant) => {
  return new Promise((resolve) => {
    let selector = "";
    if (process.env.TARO_ENV === "weapp") {
      selector = `.${ancestor} >>> .${descendant}`;
    } else {
      `.${ancestor} .${descendant}`;
    }

    Taro.createSelectorQuery()
      .selectAll(`.${ancestor} >>> .${descendant}`)
      .boundingClientRect()
      .exec((rect) => {
        resolve(rect[0]);
      });
  });
};
</script>

<style lang="less">
.common-skeleton {
}
</style>
